import sys, socket
from PyQt4 import QtGui, QtCore

HOST = '192.168.0.10'   # The remote host
PORT = 50007            # The same port as used by the server

class InputDialog(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300, 300, 430, 240)
        self.setWindowTitle('ClientDialog')

        labelH = QtGui.QLabel('HOST', self)
        labelH.move(5, 5)

        labelP = QtGui.QLabel('PORT', self)
        labelP.move(180, 5)

        self.textBrowser = QtGui.QTextBrowser(self)
        self.textBrowser.setGeometry(10, 30, 410, 200)
        
        self.button = QtGui.QPushButton('Connect', self)
        self.button.setFocusPolicy(QtCore.Qt.NoFocus)

        self.button.move(350, 1)
        self.connect(self.button, QtCore.SIGNAL('clicked()'), self.setConnect)
        self.setFocus()

        self.labelH = QtGui.QLineEdit(self)
        self.labelH.move(35, 2)
        self.labelH.setText(str(HOST))

        self.labelP = QtGui.QLineEdit(self)
        self.labelP.move(210, 2)
        self.labelP.setText(str(PORT))

    def setConnect(self):
        s = None
        self.textBrowser.setText('')
        HOST = str(self.labelH.text())
        PORT = str(self.labelP.text())
        for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
            (af, socktype, proto, canonname, sa) = res
            try:
                s = socket.socket(af, socktype, proto)
            except socket.error, msg:
                s = None
                continue
            errno = s.connect_ex(sa)
            if (errno):
                #print "Error number "+str(errno)
                s.close()
                s = None
                continue
            break
        if s is None:
            self.textBrowser.insertHtml('<H1>ERROR: Could not open socket</H1>')
        else:   
            s.send('Hello, world')
            data = s.recv(1024)
            s.close()
            self.textBrowser.insertHtml(data)

app = QtGui.QApplication(sys.argv)
icon = InputDialog()
icon.show()
app.exec_()
